package edu.scsu.csci;

import javax.servlet.ServletContext;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import edu.scsu.csci.controller.DefaultController;
import edu.scsu.csci.core.ActionURL;
import edu.scsu.csci.util.ReflectionUtil;

/**
 * Any application contorller should implement this method. 
 *
 * @author Maqbool Khan
 * @since jdk 1.5
 * @see
 * @viz.diagram IController.tpx
 */
public interface IController {
	
	/**
	 * <p>	Handles all the incoming HTTP requests.
	 * 
	 * <p>	You can implement this interface to provide your own application controller
	 * 	   	but it is recommended to use the default controller.
	 * 
	 * <p>	If you have decided to roll your own controller then it is highly recommended
	 * 	  	that you extend the edu.scsu.csci.controller.AbstractController and implement 
	 * 	  	the abstract methods before deciding to directly implement this interface. 
	 * 
	 *  
	 * @param commandURL		Wraps the command name and stratergy name to be used for this request.
	 * @param request			Servlet request.
	 * @param response			Servlet response.
	 * @return					true if exceution succeseeds without any errors else false.
	 * @see edu.scsu.csci.core.ActionURL
	 */
	boolean execute(ActionURL commandURL, ServletRequest request, ServletResponse response);
	
	/**
	 * Initializes the controller.
	 * 
	 * <p> You should implement this method to perform any onetime initializations.
	 * 
	 * @param servletContext
	 */
	void intialize(ServletContext servletContext);
	
	/**
	 * <p>Creates an instance of the controller configured for the framework.
	 * 
	 * <p>The controller class name must be specified as an intializtion parameter 
	 * for the front controller servlet.
	 * 
	 * @author Maqbool Khan
	 * @since jdk 1.5
	 * @see
	 */
	final public static class ControllerFactory	{
		
		/**
		 * singleton controller.
		 */
		private static IController controller = null;
		
		/**
		 * <p>  Creates the controller sepcified for the application based on the class name specified by
		 * 		in the webconfig.xml.
		 * 
		 * <p>	The controller class name must be specified as an intializtion parameter 
	     * 		  	for the front controller servlet.
		 * 
		 * @param servletContext
		 * @return
		 */
		public static IController create(ServletContext servletContext){
			if(controller == null){
				String controllerClassName = servletContext.getInitParameter("controllerClass");
				 
				if( controllerClassName == null) {
					controller = new DefaultController();
				}
				else{
					Class<? extends IController> contollerClass = ReflectionUtil.getClass(controllerClassName);
					controller = ReflectionUtil.instantiate(contollerClass);
				}
				controller.intialize(servletContext);
			}
			return controller;
		}
	}
}
